package migu.vr.fileutil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FileSaver
{
    public String fileName;

    public FileOutputStream fileOutputStream;

    ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();

    public FileSaver(String fileName)
    {
        this.fileName = fileName;
        try {
            this.fileOutputStream = new FileOutputStream(fileName);

            File file = new File(this.fileName);
            if (!file.exists())
            {
                file.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void write(byte[] bytes)
    {
        final byte[] buffer = bytes;
        final  FileOutputStream fileOutputStream = this.fileOutputStream;
        this.singleThreadExecutor.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    fileOutputStream.write(buffer);
                    fileOutputStream.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void close()
    {
        this.singleThreadExecutor.shutdown();
        try {
            this.fileOutputStream.close();
            this.fileOutputStream = null;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
